//连文科
//2022年7月12日14:19:37
//网络工具类
//使用dio并进行封装
import 'package:dio/dio.dart';
import 'package:dio_http_cache/dio_http_cache.dart';
import 'package:flutter/material.dart';
import 'package:lianwenke20220712/http/my_interceptors.dart';

typedef SUCCESS = void Function(dynamic data);
typedef ERROR = void Function(int code,dynamic errorMatch);

class HttpUtils{
  Dio _dio;
  static HttpUtils _httpUtils;
  HttpUtils._instent(){
    _dio = Dio(BaseOptions(
      connectTimeout: 5000,
      receiveTimeout: 5000,
      sendTimeout: 5000,
    ));
    //日志拦截器
    _dio.interceptors.add(LogInterceptor(responseBody: true,requestBody: true));
    //缓存日志拦截器
    _dio.interceptors.add(DioCacheManager(CacheConfig()).interceptor);
    //自定义日志拦截器
    _dio.interceptors.add(MyInterceptors());
  }

  //对外调用方法
  factory HttpUtils(){
    if(_httpUtils == null){
      _httpUtils = HttpUtils._instent();
    }
    return _httpUtils;
  }

  //get请求
  Future MendGet(String path,{Map<String,dynamic>map,bool isCache = false, SUCCESS onSuccess,ERROR onError}) async{
    try{
      var response = await _dio.get(path,options: isCache ? buildCacheOptions(Duration(days: 7)) : Options(),queryParameters: map);
      onSuccess(response.data);
    }on DioError catch(e){
      err(e,onError);
    }
  }

  //Post请求
  Future MendPost(String path,{Map<String,dynamic>map,bool isCache = false, SUCCESS onSuccess,ERROR onError}) async{
    try{
      var response = await _dio.post(path,options: isCache ? buildCacheOptions(Duration(days: 7)) : Options(),data: map);
      onSuccess(response.data);
    }on DioError catch(e){
      err(e,onError);
    }
  }

  void err(DioError e, ERROR onError) {
    if(e.response == null ){
      if(e.type == DioErrorType.connectTimeout || e.type == DioErrorType.receiveTimeout || e.type == DioErrorType.sendTimeout){
        onError(666,'网络错误，请检查网络');
      }else{
        onError(999,'未知错误');
      }
    }else{
      onError(e.response.statusCode,e.response.statusMessage);
    }
  }
}
